<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title>{{roomID}}</title>
  <style>
    #msglog, #messageInput {
      border: 1px solid #ccc;
      width: 500px;
      height: 350px;
      overflow-y: auto;
      font-size: 14px;
    }
    #messageInput {
      height: 80px;
    }
    .message {
      line-height: 22px;
    }
    .message .user {
      padding-right: 5px;
      padding-left: 5px;
      color: brown;
    }
    .sysMsg {
      color: #c1bfbf;
      padding-right: 5px;
      padding-left: 5px;
      font-size: 12px;
    }
    #users {
      width: 490px;
      padding: 0 5px 5px;
    }
  </style>
</head>
<body>
<div id="localView"></div>
<div id="remoteView"></div>
  用户名<input id="userName" type="text"/><button id="input">确定</button>
  <button id="joinOrLeave">退出房间</button>

  <script src="/socket.io/socket.io.js"></script>
  <script src="/js/jquery.js"></script>
  <script>

    $(function () {
	var myPc = null;
	var socket =null;
	var userName = null;
	var config={iceServers:[{
			"url": "stun:59.110.15.178:3478"
			},	
			{
				"url": "turn:59.110.15.178:3478",
				"username":"test3",
				"credential":"test3"
			}	
		]};
	navigator.mediaDevices.getUserMedia({audio:false,video: true}).then(getLocalStreamSucc,getLocalStreamFail);
	//===获取流成功===
	function getLocalStreamSucc(stream){
		window.localStream = stream;
		var localUrl = URL.createObjectURL(stream);
		$("#localView").append("<video muted src='"+localUrl+"' autoplay></video>");
	}
	//===获取流错误===						
	function getLocalStreamFail(err){
		var errMsg = "出错了 : ";
		for(var x in err){
			if(x != "constraint"){
				errMsg = errMsg + err[x] + "    ::    ";
			}else{
				//alert(JSON.stringify(err[x]));
				errMsg = errMsg + JSON.stringify(err[x]);
			}
		}
		alert(errMsg);
	}

	function createOfferSucc(offer){
		myPc.setLocalDescription(new RTCSessionDescription(offer));
		console.log('发送offer'+JSON.stringify(offer));
		socket.emit('offer', userName,JSON.stringify(offer));
		//socket.emit('offer', userName,JSON.stringify(offer.toJSON()));
		//socket.emit('offer', userName,"v=0\r\no=- 2696951877030795880 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE audio video\r\na=msid-semantic: WMS sW1wFaxN293ss03cZtfGvC2wtAI8m76aWKFZ\r\nm=audio 9 RTP/SAVPF 111 103 9 0 8 106 105 13 126\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=ice-ufrag:joX+\r\na=ice-pwd:eghfX+GNbAIwyiMwgnve49qF\r\na=fingerprint:sha-256 46:C2:57:8E:09:F1:F9:39:66:FF:70:F8:1F:C0:23:26:CB:FB:3A:56:32:03:08:50:A6:6F:A6:AD:2C:88:A5:E4\r\na=setup:actpass\r\na=mid:audio\r\na=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\na=sendrecv\r\na=rtcp-mux\r\na=rtpmap:111 opus/48000/2\r\na=fmtp:111 minptime=10;useinbandfec=1\r\na=rtpmap:103 ISAC/16000\r\na=rtpmap:9 G722/8000\r\na=rtpmap:0 PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\na=rtpmap:106 CN/32000\r\na=rtpmap:105 CN/16000\r\na=rtpmap:13 CN/8000\r\na=rtpmap:126 telephone-event/8000\r\na=ssrc:2136204930 cname:tvTCoFAZS6ncoKQt\r\na=ssrc:2136204930 msid:sW1wFaxN293ss03cZtfGvC2wtAI8m76aWKFZ 6fc81487-55c5-40d1-9d41-5ce5bf4b27c3\r\na=ssrc:2136204930 mslabel:sW1wFaxN293ss03cZtfGvC2wtAI8m76aWKFZ\r\na=ssrc:2136204930 label:6fc81487-55c5-40d1-9d41-5ce5bf4b27c3\r\nm=video 9 RTP/SAVPF 100 116 117 96\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=ice-ufrag:joX+\r\na=ice-pwd:eghfX+GNbAIwyiMwgnve49qF\r\na=fingerprint:sha-256 46:C2:57:8E:09:F1:F9:39:66:FF:70:F8:1F:C0:23:26:CB:FB:3A:56:32:03:08:50:A6:6F:A6:AD:2C:88:A5:E4\r\na=setup:actpass\r\na=mid:video\r\na=extmap:2 urn:ietf:params:rtp-hdrext:toffset\r\na=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=sendrecv\r\na=rtcp-mux\r\na=rtpmap:100 VP8/90000\r\na=rtcp-fb:100 ccm fir\r\na=rtcp-fb:100 nack\r\na=rtcp-fb:100 nack pli\r\na=rtcp-fb:100 goog-remb\r\na=rtpmap:116 red/90000\r\na=rtpmap:117 ulpfec/90000\r\na=rtpmap:96 rtx/90000\r\na=fmtp:96 apt=100\r\na=ssrc-group:FID 2226306779 3383909181\r\na=ssrc:2226306779 cname:tvTCoFAZS6ncoKQt\r\na=ssrc:2226306779 msid:sW1wFaxN293ss03cZtfGvC2wtAI8m76aWKFZ 6a143959-99b2-43cd-bac4-e18eb93d15b0\r\na=ssrc:2226306779 mslabel:sW1wFaxN293ss03cZtfGvC2wtAI8m76aWKFZ\r\na=ssrc:2226306779 label:6a143959-99b2-43cd-bac4-e18eb93d15b0\r\na=ssrc:3383909181 cname:tvTCoFAZS6ncoKQt\r\na=ssrc:3383909181 msid:sW1wFaxN293ss03cZtfGvC2wtAI8m76aWKFZ 6a143959-99b2-43cd-bac4-e18eb93d15b0\r\na=ssrc:3383909181 mslabel:sW1wFaxN293ss03cZtfGvC2wtAI8m76aWKFZ\r\na=ssrc:3383909181 label:6a143959-99b2-43cd-bac4-e18eb93d15b0\r\n");
	}

	function addStreamEvent(e){
		var remoteUrl = URL.createObjectURL(e.stream);
		$("#remoteView").append("<video src='"+remoteUrl+"' autoplay></video>");
	}

	function icecandidateEvent(evt){
		
		/*if(evt.candidate.candidate.indexOf('192.168')!=-1){
		return;
		}*/
		console.log(evt.candidate);
		socket.emit('candidate', userName,JSON.stringify(evt.candidate));
	}

	// ----------设置昵称-------------
	var userName = '';

	// ---------创建连接-----------
	function start(){
	
		socket = io();

		// 加入房间
		socket.on('connect', function () {
			socket.emit('join', userName);
		});
		socket.on('disconnect-c', function () {
			console.log("kdfkslfjsldfjldskjfldsjfdls");
		});

		socket.on('offer', function (user, Soffer) {
		
			console.log('进入offer');
			let offer = null;
			try{
				offer = JSON.parse(Soffer);
			}catch(e){
				console.log(e);
			}
			
			//console.log(Soffer);
			if(user == userName){
				return false;
			}
			let options = {	'iceRestart': true,
				    'offerToReceiveAudio': 1,
				    'offerToReceiveVideo': 1    
				};
			myPc = new RTCPeerConnection(config);
	
			myPc.oniceconnectionstatechange = function(evt){
					console.log("icecandidateEvent====>"+myPc.iceConnectionState);
					}
						
			//事件注册
			myPc.onaddstream = function(evt){
				addStreamEvent(evt);
			 };
			myPc.onicecandidate = function(evt){
				icecandidateEvent(evt);
			};
											
			myPc.addStream(window.localStream);

			myPc.setRemoteDescription(new RTCSessionDescription(offer)).then(function(){
				myPc.createAnswer().then(function(answer){
					myPc.setLocalDescription(answer);
					socket.emit('answer', userName,JSON.stringify(answer));
					//socket.emit('answer', userName,JSON.stringify(answer.toJSON()));
				});
			});
		});

		socket.on('answer', function (user, Sanswer) {
			let answer = null;
			try{
				answer = JSON.parse(Sanswer);
			}catch(e){
				console.log(e);
			}
			if(user == userName){
				return false;
			}

			//console.log(Sanswer);
			myPc.setRemoteDescription(new RTCSessionDescription(answer))
			/* .then(function(){
				myPc.createAnswer().then(function(answer){
					myPc.setLocalDescription(answer);

					socket.emit('answer', userName,JSON.stringify(answer.toJSON()));
				});
			}); */
		});

		socket.on('candidate', function (user, Scandidate) {
			console.log('candidate***'+user);
			let candidate = null;
			try{
				candidate = JSON.parse(Scandidate);
			}catch(e){
				console.log(e);
			}
			if(user == userName){
				return false;
			}

			console.log(candidate);
			myPc.addIceCandidate(new RTCIceCandidate(candidate));
		});

		// 监听消息
		socket.on('msg', function (user, msg) {
		 
		});

		// 监听系统消息
		socket.on('sys', function (user, commond) {
			console.log("==================="+user+"======="+userName+"======start===");

			if(user != userName){
				return;
			}
			if(commond === 'start'){
					
				myPc = new RTCPeerConnection(config);
				
				//事件注册
				myPc.onaddstream = function(evt){
					addStreamEvent(evt);
				 };
				myPc.onicecandidate = function(evt){
					icecandidateEvent(evt);
				};
				myPc.oniceconnectionstatechange = function(evt){
					console.log("icecandidateEvent====>"+myPc.iceConnectionState);
					}
												
				myPc.addStream(window.localStream);
				//{'OfferToReceiveAudio':true,'OfferToReceiveVideo':true}
				myPc.createOffer().then(function(offer){
					createOfferSucc(offer);
				});
			}
		});

	}
	$('#input').click(function () {
		$('#input').attr('disabled','disabled');
		userName = $('#userName').val();
		$('#userName').attr('disabled','disabled');
		start();
	});
	// 退出房间
	$('#joinOrLeave').click(function () {
		if ($(this).text() === '退出房间') {
		  $(this).text('进入房间');
		  socket.emit('leave');
		} else {
		  $(this).text('退出房间');
		  //socket.emit('join', userName);
		}

	});
    });
  </script>
</body>
</html>